package com.handsome.service.impl;

import com.github.pagehelper.PageHelper;
import com.handsome.dao.HsLogMapper;
import com.handsome.dto.BootstrapDataTableDto;
import com.handsome.entity.HsDictionary;
import com.handsome.entity.HsLog;
import com.handsome.entity.HsWidget;
import com.handsome.service.LogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private HsLogMapper hsLogMapper;

    @Override
    public int addActionLog(HsLog hsLog) {

        return hsLogMapper.insert(hsLog);
    }

    @Override
    public BootstrapDataTableDto getLogs() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        int offset = Integer.parseInt(request.getParameter("offset"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        String search = request.getParameter("search");
        BootstrapDataTableDto<HsLog> tableDto = new BootstrapDataTableDto<>();
        int count = hsLogMapper.selectCount(new HsLog());
        tableDto.setTotal(count);
        PageHelper.offsetPage(offset, limit);
        List<HsWidget> widgets = null;
        Example example = new Example(HsLog.class);
        example.setOrderByClause("id desc");

        if (!StringUtils.isBlank(search)) {
            example.createCriteria().andLike("description", search).orLike("module", search).orLike("username", search);

        } else {
            example.createCriteria().andIsNotNull("id");
        }
        List<HsLog> logs = hsLogMapper.selectByExample(example);
        tableDto.setRows(logs);
        return tableDto;
    }
}
